// *** LICENSE HEADER ***
// Filename: ./imagefunctions.cpp
// This file is part of Nodewarz 0.1
// Nodewarz is a 3d OpenGL strategy game
// Copyright (C) 2007 CZestmyr
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with this program; if not, write to the Free Software Foundation, Inc.,
// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
// *** END LICENSE HEADER ***
#include "imagefunctions.h"
#include <SDL.h>

void UnloadImage(SDL_Surface*& surface) {
    if (surface != NULL) {
        SDL_FreeSurface(surface);
        surface = NULL;
    }
}

void LoadImage(SDL_Surface*& surface, const char* image) {
    if (surface != NULL) {
        SDL_FreeSurface(surface);
    }
    surface = IMG_Load(image);
}

GLuint LoadTexture(const char* image) {
    //First, load the image as a SDL_Surface
    SDL_Surface* surface = NULL;
    LoadImage(surface, image);
    if (!surface) return 0;

    //Lock the surface to be able to work on the pixels
    SDL_LockSurface(surface);

    //Texture ID
    GLuint texture;

    //Invert the texture (so that it's not upside down)
    int height = surface->h;
    int pitch = surface->pitch;
    Uint8* pixels = (Uint8*)(surface->pixels);
    Uint8* swap = (Uint8*)malloc(pitch);
    for (int i = 0; i < height / 2; ++i) {
        memcpy(swap, pixels + pitch * i, pitch);
        memcpy(pixels + pitch * i, pixels + pitch *(height - i - 1), pitch);
        memcpy(pixels + pitch *(height - i - 1), swap, pitch);
    }
    free(swap);

    //Create the texture
    glGenTextures(1, &texture);
    glBindTexture(GL_TEXTURE_2D, texture);
    //Set the texture image and texture generation parameters
    glTexImage2D(GL_TEXTURE_2D, 0, surface->format->BytesPerPixel, surface->w,
                 surface->h, 0, GL_RGB, GL_UNSIGNED_BYTE, surface->pixels);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, _TEXTURE_FILTER);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, _TEXTURE_FILTER);

    //We can unlock the surface now
    SDL_UnlockSurface(surface);

    //Unload the auxiliary image
    UnloadImage(surface);

    //Return the generated texture ID
    return texture;
}

void UnloadTexture(GLuint texture) {
    if (texture)
        glDeleteTextures(1, &texture);
}
